import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Table,
  Select,
  Button,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { pathname } = window.location;

interface SendAPackageDetailProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: any;
  INITINFO: any;
  location: {
    query: {
      tariffId?: number;
      name?: string;
    }
  }
}

interface SendAPackageDetailState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
}

@connect(({
  SendAPackageDetail: { dataInfo },
  common: { INITINFO },
}: any) => ({ dataInfo, INITINFO }))

class SendAPackageDetailElem extends Component<SendAPackageDetailProps, SendAPackageDetailState> {
  columns: any = [
    {
      title: '序号',
      dataIndex: 'id',
      align: 'center',
      width: 80,
      render: (text: any, record: any, index: any) => {
        const { pageIndex } = this.state;
        return (
          <span key={text}>
            {((pageIndex - 1) * 20) + (index + 1)}
          </span>
        );
      },
    },
    {
      title: '省份',
      dataIndex: 'toPname',
      align: 'center',
      width: 100,
    },
    {
      title: '省编码',
      dataIndex: 'toPcode',
      align: 'center',
      width: 100,
    },
    {
      title: '首重费用',
      dataIndex: 'firstPrice',
      align: 'center',
      width: 100,
      render: (text: any) => (text / 100).toFixed(2),
    },
    {
      title: '续重费用',
      dataIndex: 'additionalPrice',
      align: 'center',
      width: 100,
      render: (text: any) => (text / 100).toFixed(2),
    },
    {
      title: '文件箱',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10909.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10909.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '文件宽箱',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10910.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10910.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '超小箱',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10904.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10904.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '超小箱-宽',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10908.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10908.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '小箱',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10903.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10903.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '小箱-宽',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10907.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10907.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '中箱',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10902.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10902.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '中箱-宽',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10906.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10906.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '大箱',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10901.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10901.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '大箱-宽',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10905.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10905.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '超大箱',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10911.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10911.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '超大箱-宽',
      children: [
        {
          title: '费用(元)',
          dataIndex: 'cellTypeObj.10912.price',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 100).toFixed(2) : '0.00'}</span>
          ),
        },
        {
          title: '时效(天)',
          dataIndex: 'cellTypeObj.10912.arriveTime',
          align: 'center',
          width: 100,
          render: (text: any) => (
            <span>{text ? (text / 24).toFixed(0) : 0}</span>
          ),
        },
      ],
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center',
      width: 160,
    },
  ];

  state: SendAPackageDetailState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
  }

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || 20,
    };
  }

  componentDidMount() {
    this.fetchAction('common/fetchAreaList');
    this.setFieldsValue();
    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    const { location: { query: { tariffId } } } = this.props;

    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
      || tariffId !== prevProps.location.query.tariffId) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => { // 设置表单
    const { searchValues: { fromPcode } } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ fromPcode });
  }

  fetchDataValues = () => {
    const params = this.getQueryParams();
    this.fetchAction('fetch', params);
  }

  getQueryParams = () => {
    const {
      searchValues: { name, ...query },
      pageIndex,
      pageSize,
    } = this.state;

    const params = {
      ...query,
      pageIndex,
      pageSize,
    };
    return params;
  }

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues }: any = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${searchValues.name}`,
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }


  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { searchValues } = this.state;
      const query = {
        ...searchValues,
        pageIndex: 1,
        pageSize: 20,
        ...values,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: `查看${searchValues.name}`,
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  }

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { searchValues: { tariffId, name } } = this.state;
    const query = { tariffId, name };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `查看${name}`,
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `SendAPackageDetail/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  }

  render() {
    const { pageIndex, pageSize } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { areaList },
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <Fragment>
        <PageHeader />

        <Card
          className="searchForm"
          bordered={false}
        >
          <Form
            className="tableListForm"
            onSubmit={this.handleSearch}
          >
            <Row gutter={12} justify="space-between">
              <Col md={6} sm={24}>
                <Form.Item label="选择省份" colon={false}>
                  {getFieldDecorator('fromPcode')(
                    <Select placeholder="请选择" allowClear={false}>
                      {areaList.map((item: any) => (
                        <Option key={String(item.id)} value={item.code}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    className="addButton smallButton marginL16"
                    type="primary"
                    onClick={this.handleReset}
                  >重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="toPname"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            bordered
            scroll={{ x: 3000 }}
            className="statementTable tableHeight60"
          />
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<SendAPackageDetailProps>()(SendAPackageDetailElem);
